package com.hzlh.core.argumentresolver;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;

import com.hzlh.core.domain.PageParameter;
import com.hzlh.core.utils.ValidateUtils;


public class PageParameterArgumentResolver implements WebArgumentResolver {

	private static Logger logger = Logger.getLogger(PageParameterArgumentResolver.class);
	@Override
	public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest)
			throws Exception {
		// TODO Auto-generated method stub
		if(methodParameter.getParameterType().equals(PageParameter.class)){
			PageParameter pageParameter = new PageParameter();
			Map<String,String[]> paramterMap = webRequest.getParameterMap();
			String[] values= null;//每个参数值
			StringBuffer value = new StringBuffer();
			String method = null;
			if(ServletWebRequest.class.isInstance(webRequest)){
				ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
				method = servletWebRequest.getRequest().getMethod();
			}
			String sort = null,order = null;
			for(Map.Entry<String, String[]> e :paramterMap.entrySet()){
				values = e.getValue();
				if(values!=null && values.length >0){
					value.delete(0, value.length());
					for(String v:values){
						value.append(","+v);
					}
					if(value.length()>0){
						value.delete(0,1);
						if(StringUtils.equalsIgnoreCase(e.getKey(), "sort")){
							sort = value.toString();
						}else if(StringUtils.equalsIgnoreCase(e.getKey(), "order")){
							order = value.toString();
						}else{
							pubValueToPageParameter(pageParameter, value, method, e.getKey());
						}
						
					}
				}
			}
			StringBuffer sortString = new StringBuffer();
			if (sort != null) {
				sortString.append(sort);
				if (order != null) {
					sortString.append(" " + order);
				}
			}
			pageParameter.setSort(sortString.toString());
			return pageParameter;
		}
		return UNRESOLVED;
	}
	private void pubValueToPageParameter(PageParameter pageParameter, StringBuffer value, String method,
			String key) {
		// String v = value[0].trim().replace("'", "''");
		String v = value.toString().trim();

		if (StringUtils.isNotBlank(v)) {
			if (logger.isDebugEnabled()) {
				logger.debug("pub query key [" + key + "] value ["+v+"]");
			}

			if (StringUtils.equalsIgnoreCase(key, "pageNo")) {
				if (ValidateUtils.isInteger(v)) {
					pageParameter.setPageNo(Integer.valueOf(v));
				}
			} else if (StringUtils.equalsIgnoreCase(key, "pageSize")) {
				if (ValidateUtils.isInteger(v)) {
					pageParameter.setPageSize(Integer.valueOf(v));
				}
			} else {
				pageParameter.addQueryFilter(key, v);
			}
		}
	}
}
